import React, {useEffect, useRef, useState} from "react";
import style from './emoji.module.scss'
import type {UploadProps} from 'antd';
import {Button, Card ,Upload} from 'antd';
import {CompassOutlined, FileImageOutlined, PaperClipOutlined, SmileOutlined} from '@ant-design/icons'
import {emojiList} from "./emojiList";
/**
 *
 */
interface emojiInfo {
    width?: number,
    row?: number,
    inputValue?: Function,
    placeholder?: string,
    height?: number
}
export default function Emoji(prop: emojiInfo) {
    let [showEmoji, setShowEmoji] = useState(false)
    let [showBox, setShowBox] = useState(false)
    let [inputValue, setInputValue] = useState("")
    //保存图片
    let [imgList,setimgList]=useState<string[]>([])
    let suiji=Math.random()*(1000000000000000000000000000000000-1)+1
    //上传的信息
    const imgProp: UploadProps = {
        showUploadList:false,
        name: 'img',
        action: 'http://api_devss.wanxikeji.cn/api/savePic',
        // headers: {
        //     authorization: 'authorization-text',
        // },
        onChange(info) {
            if (info.file.status !== 'uploading') {
                if(info.file.response.code===2000){
                    let List=imgList
                    List.push(`http://api_devss.wanxikeji.cn/${info.file.response.data}`)
                    setimgList(List)
                    getSelectPos()
                }
            }
            if (info.file.status === 'error') {
                console.log(`${info.file.name} file upload failed.`)
            }
        },
    };

    return (

        <div style={{width: prop.width ? prop.width + 'px' : '450px'}}>
            <div>
                <div
                    className={showBox?`${style.active_input_box} ${style.input_box}`:style.input_box}
                    style={{height:prop.height+"px"}}
                    onClick={()=>{btBox()}}
                >
                {/*输入区*/}
                    <div
                        contentEditable={true}
                        id={suiji+"context"}
                        className={style.context}
                        suppressContentEditableWarning={true}
                        placeholder={prop.placeholder}
                        onInput={(e)=>{ChangeInput(e)}}
                        tabIndex= {-1}
                        onBlur={()=>{setShowBox(false)}}
                        onFocus={()=>{setShowBox(true)}}
                    >
                    </div>
                {/*    图片*/}
                    {
                        imgList.length>0?<div className={style.boxImg}>
                            <div id={suiji+"img"}>
                                {
                                    imgList!.map(item=>{
                                        return <img src={item} alt="" style={{width:"80px",height:"80px"}} key={item}/>
                                    })
                                }
                            </div>
                        </div>:null
                    }
                </div>
                {/*    图片*/}
                <div className={style["emoji-bottom"]}>
                    <div className={style["emoji-bottom-left"]}>
                        <div className={showEmoji ? `${style['emoji-bottom-left-nav']} ${style["active-emoji-nav"]}`: style["emoji-bottom-left-nav"]}
                             onClick={() => {
                                 btEmoji()
                             }}>
                            <SmileOutlined/>
                            <div>表情</div>
                        </div>

                           <Upload className={style["emoji-bottom-left-nav"]} {...imgProp}>
                              <div style={{display:"flex",alignItems:"center"}}>
                                  <FileImageOutlined/>
                                  <div>图片</div>
                              </div>
                           </Upload>

                        <div className={style["emoji-bottom-left-nav"]}>
                            <PaperClipOutlined/>
                            <div>链接</div>
                        </div>
                        <div className={style["emoji-bottom-left-nav"]}>
                            <CompassOutlined/>
                            <div>话题</div>
                        </div>
                    </div>
                    <div><Button type="primary" onClick={() => {
                        comment()
                    }} disabled={!inputValue.trim()}>发表评论</Button></div>
                    {
                        showEmoji ? <Card className={style["emoji-box"]} id="emojiBox">
                            <div>全部</div>
                            <div>
                                {
                                    emojiList.map((item: any) => {
                                        return <span className={style["emoji-icon"]} key={item.id} onClick={() => {
                                            btEmojiIcon(item.emoji)
                                        }}>{item.emoji}</span>
                                    })
                                }
                            </div>
                        </Card> : null
                    }
                </div>
            </div>
        </div>
    )

    /**
     * 点击表情显示
     */
    function btEmoji() {
        setShowEmoji(!showEmoji)
        if (!showEmoji) {
            getSelectPos()
        }
    }

    /**
     * 输入框变化
     */
    function ChangeInput(e: any) {
        getInputValue()
    }

    /**
     * 点击某个表情
     * @param text
     */
    function btEmojiIcon(text: any) {
        document.getElementById('emojiBox')!.addEventListener("mousedown",(event)=>{
            event.preventDefault();
            return false;
        });
        getSelectPos()
        insertContent(text)
        getInputValue()
    }

    /**
     * 获取输入框的值
     */
    function getInputValue(){
        let content=document.getElementById(suiji+"context")
        setInputValue(content!.innerHTML)
    }

    /**
     * 点击盒子获取焦点
     */
    function btBox(){
        setShowBox(true)
        getSelectPos()
    }
    /**
     * 发表评论
     */
    function comment() {
        let img=document.getElementById(suiji+"img")
        let newImg
        if(img){
            newImg=img.innerHTML
        }
        prop.inputValue!({
            value:inputValue,
            img:newImg
        })
        setInputValue("")

           document.getElementById(suiji+"context")!.innerHTML=""

        setimgList([])
    }


    /**
     * 在根据光标位置插入内容
     * @param content
     */

    function insertContent(content: any) {
        if (!content) {//如果插入的内容为空则返回
            return;
        }
        let sel = null;
        sel = window.getSelection();
        if (sel!.rangeCount > 0) {
            let range = sel!.getRangeAt(0);      //获取选择范围
            range.deleteContents();             //删除选中的内容
            let el = document.createElement("div"); //创建一个空的div外壳
            el.innerHTML = content;                 //设置div内容为我们想要插入的内容。
            let frag = document.createDocumentFragment();//创建一个空白的文档片段，便于之后插入dom树
            let node = el.firstChild;
            let lastNode = frag.appendChild(node!);
            range.insertNode(frag);                 //设置选择范围的内容为插入的内容
            let contentRange = range.cloneRange();  //克隆选区
            contentRange.setStartAfter(lastNode);          //设置光标位置为插入内容的末尾
            contentRange.collapse(true);                   //移动光标位置到末尾
            sel!.removeAllRanges();                  //移出所有选区
            sel!.addRange(contentRange);             //添加修改后的选区
        }
    }

    /**
     * 在末尾获取焦点
     * @param obj 元素id
     */
    function getSelectPos() {
        let esrc = document.getElementById(suiji+"context");
        let range = document.createRange();
        range.selectNodeContents(esrc! as Node);
        range.collapse(false);
        let sel = window.getSelection();
        sel!.removeAllRanges();
        sel!.addRange(range);
    }

}
